package sicnu.cs.ich.user.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.stereotype.Service;
import sicnu.cs.ich.common.services.impl.RedisService;
import sicnu.cs.ich.common.util.keyCryptor.AESUtil;
import sicnu.cs.ich.common.util.keyCryptor.RSAUtil;
import sicnu.cs.ich.user.service.IEncryptKey;

import java.util.Map;

/**
 * @author CaiKe
 * @date 2021/11/30 16:01
 */
@Service
@RequiredArgsConstructor
public class EncryptKeyImpl implements IEncryptKey {

    private final RedisService redisService;
    private final static String REDIS_AES_KEY = "AES::key";
    private final static String REDIS_RSA_SEC_KEY = "RSA::key::sec";
    private final static String REDIS_RSA_PUB_KEY = "AES::key::pub";

    @Override
    public String generateAESKey() {
        val redis_key = redisService.getValue(REDIS_AES_KEY);
        if (redis_key != null) {
            return (String) redis_key;
        }
        // Redis无缓存，则生成
        final String key = AESUtil.generateKey();
        redisService.cacheValue(REDIS_AES_KEY, key, -1);
        return key;
    }

    @Override
    public String[] generateRSAKeys() {
        val redis_pubKey = redisService.getValue(REDIS_RSA_PUB_KEY);
        val redis_secKey = redisService.getValue(REDIS_RSA_SEC_KEY);
        if (redis_pubKey != null && redis_secKey != null) {
            return new String[]{(String) redis_pubKey, (String) redis_secKey};
        }
        // Redis无缓存，则生成
        final Map<String, String> keys = RSAUtil.createKeys(1024);
        val pubKey = keys.get(RSAUtil.PUBLIC_KEY);
        val secKey = keys.get(RSAUtil.PRIVATE_KEY);
        redisService.cacheValue(REDIS_RSA_PUB_KEY, pubKey, -1);
        redisService.cacheValue(REDIS_RSA_SEC_KEY, secKey, -1);
        return new String[]{pubKey, secKey};
    }


}